package yannan.voiplock4ble.net.base;

import android.util.Log;


import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import yannan.voiplock4ble.BuildConfig;

/**
 * <p>name:</p>
 * <p>describe: 网络请求返回类</p>
 *
 * @author Maintel
 * @time 2016/9/20 15:20
 */
public abstract class NetworkCallBack<T> implements Callback<T> {
    @Override
    public void onResponse(Call<T> call, Response<T> response) {
        if (BuildConfig.DEBUG) Log.e("NetworkCallBack", "response.code():" + response.code());
        if (response.code() == 200) {
            try {
                T test = response.body();
                if (test != null) {
                    onSuc(test);
                } else {
                    onFail("联网失败");
                }

            } catch (Exception e) {
                e.printStackTrace();
                String msg = null;
                try {
                    msg = (String) response.body();
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
                if (msg == null) {
                    msg = "error";
                }
                if (BuildConfig.DEBUG) Log.e("NetworkCallBack", msg);
                onFail(msg);
            }
        } else {
            onFail("联网失败" + response.code());
        }
    }

    @Override
    public void onFailure(Call<T> call, Throwable t) {
        if (t.getMessage() != null) {
            onFail(t.getMessage());
        } else {
            onFail("联网失败");
        }
    }

    public abstract void onSuc(T resBody);

    public abstract void onFail(String msg);
}
